/**
 *   颜色渐变
 *   num：颜色个数
 */
function fColorGradualChange (startColor, endColor, num) {
  if (num === 1) {
    return [endColor]
  }
  var rgb = /^rgb|RGB\((([0-9]|[1-9]\d|1\d\d|2([0-4]\d|5[0-5])),){2}([0-9]|[1-9]\d|1\d\d|2([0-4]\d|5[0-5]))\)$/ // rgb
  var hex = /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i // 16进制
  // 颜色预处理
  var startRGB, endRGB
  if (hex.test(startColor)) {
    startRGB = fAnalysisRGB(startColor)
  } else if (rgb.test(startColor)) {
    startRGB = startColor.substring(3, 15).split(',')
  }
  if (hex.test(endColor)) {
    endRGB = fAnalysisRGB(endColor)
  } else if (rgb.test(startColor)) {
    endRGB = endColor.substring(3, 15).split(',')
  }
  var startR = startRGB[0]
  var startG = startRGB[1]
  var startB = startRGB[2]
  var endR = endRGB[0]
  var endG = endRGB[1]
  var endB = endRGB[2]

  var sR = (endR - startR) / num
  var sG = (endG - startG) / num
  var sB = (endB - startB) / num

  var colors = []
  for (var i = 0; i < num; i++) {
    if (i === 0) {
      colors.push(startColor)
    } else if (i === num - 1) {
      colors.push(endColor)
    } else {
      colors.push(fColorToHex(parseInt((sR * i + startR)), parseInt((sG * i + startG)), parseInt((sB * i + startB))))
    }
  }
  return colors
}

/**
 *   解析rgb格式
 */
function fAnalysisRGB (color) {
  color = color.toLowerCase().substring(1, color.length)
  var colors = []
  colors.push(parseInt(color.substring(0, 2), 16))
  colors.push(parseInt(color.substring(2, 4), 16))
  colors.push(parseInt(color.substring(4, 6), 16))
  return colors
}

/**
 *   rgb转hex
 */
function fColorToHex (r, g, b) {
  var hex = '#' + fAddZero(r.toString(16)) + fAddZero(g.toString(16)) + fAddZero(b.toString(16))
  return hex
}

/**
 *   加0补位
 */
function fAddZero (v) {
  var newv = '00' + v
  return newv.substring(newv.length - 2, newv.length)
}

export default fColorGradualChange
